from docx import Document
import xlwt
import util
import arial10

# excel表头
excel_header = ["题干", "题型", "选择项1", "选择项2", "选择项3", "选择项4", "选择项5",
                "选择项6", "解析", "答案1", "答案2", "得分1", "得分2"]
# 选项位置映射
option_locate_map = {"A": 2, "B": 3, "C": 4, "D": 5, "E": 6, "F": 7}


# 获取加粗居中样式
def get_title_style():
    # 创建样式
    style = xlwt.XFStyle()
    # 设置字体 加粗 15号字体
    font = xlwt.Font()
    font.name = "宋体"
    font.bold = True
    font.height = 20 * 12
    style.font = font
    # 设置水平垂直居中
    alignment = xlwt.Alignment()
    # 0x01(左端对齐)、0x02(水平方向上居中对齐)、0x03(右端对齐)
    alignment.horz = 0x02
    # 0x00(上端对齐)、 0x01(垂直方向上居中对齐)、0x02(底端对齐)
    alignment.vert = 0x01
    style.alignment = alignment
    return style


# docx文件转换
def docx_transfer(src, des):
    # 读取docx文件
    document = Document(src)
    # 创建excel与sheet并写入表头
    wk = xlwt.Workbook(encoding="utf-8")
    sheet = util.FitSheetWrapper(wk.add_sheet("题库", cell_overwrite_ok=True))
    for idx, item in enumerate(excel_header):
        sheet.write(0, idx, item, get_title_style())
    # 解析docx并且写入excel内容
    cur_question_body = ""
    cur_option = ""
    cur_option_body = ""
    line_num = 0
    # 单选多选处理
    for p in document.paragraphs:
        line = p.text.strip()
        # 字母匹配
        if util.match_alpha_start(line):
            # 写入题干
            if cur_question_body:
                sheet.write(line_num, 0, cur_question_body)
                cur_question_body = ""
            # 提取选项与选项主体
            cur_option = line[0]
            cur_option_body = line[2:]
        # 数字匹配
        elif util.match_num_start(line):
            cur_question_body += line
            line_num += 1
        else:
            if cur_option_body:
                cur_option_body += line
            if cur_question_body:
                cur_question_body += line
        # 写入选项
        if cur_option:
            sheet.write(line_num, option_locate_map[cur_option], cur_option_body)
            cur_option = ""
            cur_option_body = ""
    # 保存退出
    wk.save(des)


if __name__ == '__main__':
    docx_transfer("test.docx", "desc.xlsx")
